using B.S.Database.ErrorCode;
using B.S.Database.Read.Api.Dtos.RequsetDtos;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SkiaSharp;
using System;
using System.IO;
using System.Text;

namespace B.S.Database.Read.Api.Controllers
{
    /// <summary>
    /// 验证码控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    [Authorize]
    public class VerifyCodeController : ControllerBase
    {
        /// <summary>
        /// 获取验证码（纯文字）
        /// </summary>
        /// <param name="guid">可选，前台传入的guid</param>
        /// <returns>验证码和guid</returns>
        [HttpGet]
        [AllowAnonymous]
        public Apiresult<VerifyCodeDto> GetVerifyCode([FromQuery] string? guid = null)
        {
            var result = new Apiresult<VerifyCodeDto>();
            string code = GenerateCode(4);
            string codeGuid = string.IsNullOrWhiteSpace(guid) ? Guid.NewGuid().ToString() : guid;
            result.Code = ApiEnums.成功;
            result.Message = "成功";
            result.Data = new VerifyCodeDto
            {
                Guid = codeGuid,
                Code = code
            };
            return result;
        }

        /// <summary>
        /// 获取图片验证码
        /// </summary>
        /// <param name="guid">可选，前台传入的guid</param>
        /// <param name="width">图片宽度，默认120</param>
        /// <param name="height">图片高度，默认40</param>
        /// <param name="length">验证码长度，默认4</param>
        /// <returns>图片验证码的Base64字符串和guid</returns>
        [HttpGet]
        [AllowAnonymous]
        public Apiresult<object> GetImageVerifyCode([FromQuery] string? guid = null, int width = 120, int height = 40, int length = 4)
        {
            var result = new Apiresult<object>();
            string code = GenerateCode(length);
            string codeGuid = string.IsNullOrWhiteSpace(guid) ? Guid.NewGuid().ToString() : guid;
            string imageBase64;
            using (var surface = SKSurface.Create(new SKImageInfo(width, height)))
            {
                var canvas = surface.Canvas;
                var random = new Random();
                // 填充背景色
                canvas.Clear(SKColors.White);

                // 添加干扰线
                using (var paint = new SKPaint
                {
                    Color = SKColors.LightGray,
                    StrokeWidth = 1,
                    IsAntialias = true
                })
                {
                    for (int i = 0; i < 5; i++)
                    {
                        int x1 = random.Next(width);
                        int y1 = random.Next(height);
                        int x2 = random.Next(width);
                        int y2 = random.Next(height);
                        canvas.DrawLine(x1, y1, x2, y2, paint);
                    }
                }

                // 添加干扰点
                using (var paint = new SKPaint
                {
                    Color = SKColors.LightGray,
                    IsAntialias = true
                })
                {
                    for (int i = 0; i < 50; i++)
                    {
                        int x = random.Next(width);
                        int y = random.Next(height);
                        canvas.DrawCircle(x, y, 0.5f, paint);
                    }
                }

                // 绘制验证码文字
                using (var paint = new SKPaint
                {
                    IsAntialias = true,
                    TextAlign = SKTextAlign.Center,
                    TextSize = height * 0.6f
                })
                {
                    // 为每个字符添加随机颜色和位置偏移
                    for (int i = 0; i < code.Length; i++)
                    {
                        paint.Color = GetRandomColor();
                        var charX = (width / (float)code.Length) * i + (width / (float)code.Length) / 2 + random.Next(-3, 4);
                        var charY = height / 2f + random.Next(-2, 3);
                        canvas.DrawText(code[i].ToString(), charX, charY, paint);
                    }
                }

                // 转换为Base64
                using (var image = surface.Snapshot())
                using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
                {
                    imageBase64 = Convert.ToBase64String(data.ToArray());
                }
            }
            // 构造图片URL
            string imageUrl = Url.Action("GetImageVerifyCodeFile", new { guid = codeGuid, width, height, length });
            result.Code = ApiEnums.成功;
            result.Message = "成功";
            result.Data = new
            {
                Guid = codeGuid,
                Code = code,
                ImageBase64 = imageBase64,
                ImageUrl = imageUrl
            };
            return result;
        }

        /// <summary>
        /// 生成指定长度的纯文字验证码
        /// </summary>
        private string GenerateCode(int length)
        {
            const string chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
            var random = new Random();
            var sb = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                sb.Append(chars[random.Next(chars.Length)]);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 生成图片验证码
        /// </summary>
        /// <param name="code">验证码文字</param>
        /// <param name="width">图片宽度</param>
        /// <param name="height">图片高度</param>
        /// <returns>Base64编码的图片字符串</returns>
        private string GenerateImageCode(string code, int width, int height)
        {
            using (var surface = SKSurface.Create(new SKImageInfo(width, height)))
            {
                var canvas = surface.Canvas;
                var random = new Random();

                // 填充背景色
                canvas.Clear(SKColors.White);

                // 添加干扰线
                using (var paint = new SKPaint
                {
                    Color = SKColors.LightGray,
                    StrokeWidth = 1,
                    IsAntialias = true
                })
                {
                    for (int i = 0; i < 5; i++)
                    {
                        int x1 = random.Next(width);
                        int y1 = random.Next(height);
                        int x2 = random.Next(width);
                        int y2 = random.Next(height);
                        canvas.DrawLine(x1, y1, x2, y2, paint);
                    }
                }

                // 添加干扰点
                using (var paint = new SKPaint
                {
                    Color = SKColors.LightGray,
                    IsAntialias = true
                })
                {
                    for (int i = 0; i < 50; i++)
                    {
                        int x = random.Next(width);
                        int y = random.Next(height);
                        canvas.DrawCircle(x, y, 0.5f, paint);
                    }
                }

                // 绘制验证码文字
                using (var paint = new SKPaint
                {
                    IsAntialias = true,
                    TextAlign = SKTextAlign.Center,
                    TextSize = height * 0.6f
                })
                {
                    // 为每个字符添加随机颜色和位置偏移
                    for (int i = 0; i < code.Length; i++)
                    {
                        paint.Color = GetRandomColor();
                        var charX = (width / (float)code.Length) * i + (width / (float)code.Length) / 2 + random.Next(-3, 4);
                        var charY = height / 2f + random.Next(-2, 3);
                        canvas.DrawText(code[i].ToString(), charX, charY, paint);
                    }
                }

                // 转换为Base64
                using (var image = surface.Snapshot())
                using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
                {
                    byte[] imageBytes = data.ToArray();
                    return Convert.ToBase64String(imageBytes);
                }
            }
        }

        /// <summary>
        /// 获取随机颜色
        /// </summary>
        private SKColor GetRandomColor()
        {
            var random = new Random();
            var colors = new SKColor[]
            {
                SKColors.DarkBlue,
                SKColors.DarkGreen,
                SKColors.DarkRed,
                SKColors.DarkOrange,
                SKColors.Purple,
                SKColors.Brown,
                SKColors.DarkCyan
            };
            return colors[random.Next(colors.Length)];
        }
        /// <summary>
        /// 生成图片验证码
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public IActionResult GetImageVerifyCodeFile([FromQuery] string? guid = null, int width = 120, int height = 40, int length = 4)
        {
            string code = GenerateCode(length);
            using (var surface = SKSurface.Create(new SKImageInfo(width, height)))
            {
                var canvas = surface.Canvas;
                var random = new Random();
                // 填充背景色
                canvas.Clear(SKColors.White);
                // 添加干扰线
                using (var paint = new SKPaint { Color = SKColors.LightGray, StrokeWidth = 1, IsAntialias = true })
                {
                    for (int i = 0; i < 5; i++)
                    {
                        int x1 = random.Next(width);
                        int y1 = random.Next(height);
                        int x2 = random.Next(width);
                        int y2 = random.Next(height);
                        canvas.DrawLine(x1, y1, x2, y2, paint);
                    }
                }
                // 添加干扰点
                using (var paint = new SKPaint { Color = SKColors.LightGray, IsAntialias = true })
                {
                    for (int i = 0; i < 50; i++)
                    {
                        int x = random.Next(width);
                        int y = random.Next(height);
                        canvas.DrawCircle(x, y, 0.5f, paint);
                    }
                }
                // 绘制验证码文字
                using (var paint = new SKPaint { IsAntialias = true, TextAlign = SKTextAlign.Center, TextSize = height * 0.6f })
                {
                    for (int i = 0; i < code.Length; i++)
                    {
                        paint.Color = GetRandomColor();
                        var charX = (width / (float)code.Length) * i + (width / (float)code.Length) / 2 + random.Next(-3, 4);
                        var charY = height / 2f + random.Next(-2, 3);
                        canvas.DrawText(code[i].ToString(), charX, charY, paint);
                    }
                }
                using (var image = surface.Snapshot())
                using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
                {
                    return File(data.ToArray(), "image/png");
                }
            }
        }
    }
} 